function varargout = TLProductDlg(action,varargin)

% TL_PRODUCT_DLG manages the user interface for TargetLink Product block
%
% SYNTAX dlgInfo = TLProductDlg('GetDlgInfo');
%   gets dialog info of TargetLink Constant block
%
%   INPUT ARGUMENTS
%   -/-      
%
%   OUTPUT ARGUMENTS
%   dlgInfo     dialog information contains pageNames etc.
%
% SYNTAX [sheetDims, ctrlPos] = TLProductDlg('CtrlPositions', pageName, commonGeom, dlgInfo, sheetDims);
%   calculates the control positions of all controls of dialog page: <pageName>
%
%   INPUT ARGUMENTS
%   pageName        name of current page
%   commonGeom      common geometry data
%   dlgInfo         dialog information contains pageNames etc.
%   sheetDims       dimension of sheet
%
%   OUTPUT ARGUMENTS
%   sheetDims       modified dimension of sheet
%   ctrlPos         positions of controls
%
% SYNTAX dlgdata = TLProductDlg('Create', pageName, dlgfig, dlgdata);
%   creates all controls of dialog page: <pageName>
%
%   INPUT ARGUMENTS
%   pageName        name of current page
%   dlgfig          figure handle
%   dlgdata         dialog data
%
%   OUTPUT ARGUMENTS
%   dlgdata         modified dialog data
%
% SYNTAX [dlgdata,bModified] = TLProductDlg('Manage', pageName, dlgfig, dlgdata, pageAction);
%   manages all actions of dialog page: <pageName>
%
%   INPUT ARGUMENTS
%   pageName        name of current page
%   dlgfig          figure handle
%   dlgdata         dialog data
%   pageAction      modified control of current page
%
%   OUTPUT ARGUMENTS
%   dlgdata         modified dialog data
%   bModified       flag = 1, if dialog data are modified, =0 otherwise
%
% SYNTAX dlgdata = TLProductDlg('Update', dlgfig, dlgdata, pageNum);
%   updates all controls of dialog page: <pageNum>
%
%   INPUT ARGUMENTS
%   dlgfig          figure handle
%   dlgdata         dialog data
%   pageNum         number of current page
%
%   OUTPUT ARGUMENTS
%   dlgdata         modified dialog data
%
% SYNTAX TLProductDlg('Apply', dlgfig, dlgdata);
%   writes current blockdata to block and DD
%
%   INPUT ARGUMENTS
%   dlgfig      handle for dialog figure
%   dlgdata     dialog data
%
%   OUTPUT ARGUMENTS
%   - / -


% Author(s): D. Andoleit, T. Pietzsch
% $RCSfile: TLProductDlg.m $
% $ProjectName: e:/ARC/Components/HostSW/SimulinkBlocksets/TLBlocksets/CommonBlockset/CommonBlockset_SimBlocksUI/Sources/MSrc/project.pj $
% $Revision: 1.13 $
% $Date: 2011/03/17 11:57:55MEZ $
%
% Copyright ?2011 dSPACE GmbH. All rights reserved.


switch action

    case 'GetDlgInfo'
        hBlock = varargin{1};
        dlgInfo = tl_get_dlginfodefaults('tlsim');
        titleName = 'Product';
        pathinfo = tl_pathinfo(hBlock);
        dlgInfo.title = sprintf('TargetLink %s: %s', titleName, pathinfo.shortDisplayName);
        dlgInfo.pageNames   = {
            'Output';...
            'Logging & Autoscaling';...
            'Documentation'};
        varargout{1} = dlgInfo;
        varargout{2} = get_tlcg_data(hBlock);

    case 'CtrlPositions'
        pageName     = varargin{1};
        commonGeom   = varargin{2};
        sheetDims    = varargin{4};
        switch pageName
            case 'Output'
                [sheetDims, ctrlPos] = FcnOutputCtrlPositions(commonGeom);
                
            case 'Logging & Autoscaling'
                excludedCtrls = {'keepParameter'};
                [sheetDims, ctrlPos] = ...
                    TLManageLoggingCtrls('calcCtrls', commonGeom, sheetDims, excludedCtrls);

            case 'Documentation'
                bTblBlock = 0;
                bCodeComment = 1;
                [sheetDims,ctrlPos] = ...
                    TLManageDocCtrls('ctrlpos',commonGeom,sheetDims,bCodeComment,bTblBlock);
        end
        varargout{1} = sheetDims;
        varargout{2} = ctrlPos;

    case 'Create'
        pageName = varargin{1};
        dlgfig   = varargin{2};
        dlgdata  = varargin{3};
        pageNum  = strmatch(pageName,dlgdata.pageNames,'exact');
        switch pageName
            case 'Output'
                dlgdata = ...
                    FcnCreateOutputPage(pageNum,dlgfig,dlgdata);
            case 'Logging & Autoscaling'
                dlgdata = ...
                    TLManageLoggingCtrls('create',pageNum,dlgfig,dlgdata);
            case 'Documentation'
                dlgdata = ...
                    TLManageDocCtrls('create',pageNum,dlgfig,dlgdata);
        end
        dlgdata.pageData{pageNum}.ctrlPos = [];
        varargout{1} = dlgdata;

    case 'Manage',
        pageName   = varargin{1};
        dlgfig     = varargin{2};
        dlgdata    = varargin{3};
        pageAction = varargin{4};
        pageNum    = strmatch(pageName,dlgdata.pageNames,'exact');
        switch pageName
            case 'Output'
                [dlgdata,bModified] = ...
                    FcnManageOutputPage(pageNum,dlgfig,dlgdata,pageAction);
                
            case 'Logging & Autoscaling'
                [dlgdata, bModified] = ...
                    TLManageLoggingCtrls('manage', pageNum, dlgdata, pageAction, 'logdata');

            case 'Documentation'
                [dlgdata,bModified] = ...
                    TLManageDocCtrls('callback',pageNum,dlgfig,dlgdata,pageAction);
        end
        varargout{1} = dlgdata;
        varargout{2} = bModified;

    case 'ManageSystemIcons',
        dlgfig     = varargin{1};
        dlgdata    = varargin{2};
        pageAction = varargin{3};
        [dlgdata, bModified] = FcnManageSystemIcons(dlgfig,dlgdata,pageAction);
        varargout{1} = dlgdata;
        varargout{2} = bModified;

    case 'Update'
        dlgfig  = varargin{1};
        dlgdata = varargin{2};
        pageNum = varargin{3};
        pageName  = dlgdata.pageNames{pageNum};
        switch pageName
            case 'Output'
                dlgdata = FcnUpdateOutputPage(dlgdata,dlgfig,pageNum);
                
            case 'Logging & Autoscaling'
                dlgdata =  TLManageLoggingCtrls('update',pageNum,dlgdata,'logdata','output');
                TLManageLoggingCtrls('setCtrls',pageNum, dlgfig, dlgdata);
                
            case 'Documentation'
                TLManageDocCtrls('update', pageNum, dlgfig, dlgdata);
        end
        varargout{1} = dlgdata;

    case 'Apply'
        dlgdata  = varargin{2};
        bClose   = varargin{3};
        [dlgdata, bClose] = tl_apply_blockdata(dlgdata, bClose);
        varargout{1} = dlgdata;
        varargout{2} = bClose;

    otherwise
        error(['Invalid action "' action '"']);
end


%-----------------------------------------------------------------------------------------
% FcnManageSystemIcons manage actions of toolbar icons
%
% INPUT ARGUMENTS
%   dlgfig      handle for dialog figure
%   dlgdata     dialog data
%   action      action at one control of current page
%
% OUTPUT ARGUMENTS
%   dlgdata     modified dialog data
%   bModified   flag = 1, if dialog data are modified, =0 otherwise
%-----------------------------------------------------------------------------------------
function [dlgdata, bModified] = FcnManageSystemIcons(dlgfig, dlgdata, action) %#ok

bModified = false;
switch action
    case 'EditCode'
        % look for associated production code file
        [codefile,blockstr] = get_codefile(dlgdata.model);
        if ~isempty(codefile)
            codeedit(codefile,blockstr);
        end

    case 'ViewCode'
        tl_create_links_to_model('ShowComputation',dlgdata.model, 'output');

    otherwise
        error('Invalid callback');

end % switch(action)


%-----------------------------------------------------------------------------------------
% FcnOutputCtrlPositions calculates positions for all controls on output page
%
% INPUT ARGUMENTS
%   commonGeom      common geometrie information
%
% OUTPUT ARGUMENTS
%   sheetDims       modified dimension of sheet
%   ctrlPos         positions of controls
%
% HINT:
% Positions are calculated from the bottom left of the figure to avoid
% dependencies on figure size
%-----------------------------------------------------------------------------------------
function [sheetDims, ctrlPos] = FcnOutputCtrlPositions(commonGeom)

excludedCtrls = {'inheritproperties'};
[sheetDims, ctrlPos, col, colDelta, rowDelta] = ...
    tl_calc_ctrls_positions(commonGeom,excludedCtrls);

[prodinputsLabelSize, exceptionCheckboxSize] = ...
    ds_get_uicontrol_sizes(commonGeom, ...
    {'Number of inputs:', 'text';
    'Protect against division by zero in production code', 'checkbox' });

% control positions of controls of additional group box
cy = commonGeom.frameBottomEdgeBuffer;

% input sign label
cx = col(1);
ctrlPos.prodinputsLabel = [cx cy prodinputsLabelSize];

% input sign edit field
cx = col(1) + prodinputsLabelSize(1) + 5;
ctrlPos.prodinputsEdit = [cx cy ctrlPos.lsbEdit(3:4)];

% exception handling checkbox
cx = col(4);
ctrlPos.exceptionCheckbox = [cx cy exceptionCheckboxSize];

% increase sheet dimensions
sheetDims(2) = sheetDims(2) ...
    + ctrlPos.addoptGroupbox(4) ...
    + commonGeom.textHeight;


%-----------------------------------------------------------------------------------------
% FcnCreateOutputPage creates the figure window
%
% INPUT ARGUMENTS
%   pageNum     number of current page
%   dlgfig      handle for dialog figure
%   dlgdata     dialog data
%
% OUTPUT ARGUMENTS
%   dlgdata     modified dialog data
%-----------------------------------------------------------------------------------------
function dlgdata = FcnCreateOutputPage(pageNum,dlgfig,dlgdata)

% create all controls
dlgdata = TLManageVariableCtrls('create', pageNum, dlgfig, dlgdata);
dlgdata = TLManageScalingCtrls('create', pageNum, dlgfig, dlgdata);

ctrlPos = dlgdata.pageData{pageNum}.ctrlPos;
Children = dlgdata.pageData{pageNum}.children;
pageName = dlgdata.pageNames{pageNum};

inputslabeltext = 'Number of inputs:';
inputsLabelPos  = ctrlPos.prodinputsLabel;
inputsEditPos   = ctrlPos.prodinputsEdit;

Children.addoptGroupbox = uipanel( ...
    'Parent',            dlgfig, ...
    'Title',            {'Inputs and exception handling'}, ...
    'Units',            'pixels', ...
    'Position',          ctrlPos.addoptGroupbox);

% inputs controls
Children.inputsLabel = uicontrol( ...
    'Parent',             Children.addoptGroupbox, ...
    'Style',              'text', ...
    'String',             inputslabeltext, ...
    'Position',           inputsLabelPos);

Children.inputsEdit = uicontrol( ...
    'Parent',             Children.addoptGroupbox, ...
    'BackgroundColor',    'w', ...
    'Style',              'edit', ...
    'Position',           inputsEditPos, ...
    'Callback',           sprintf('tldlg(''%s'',gcbf,''inputsEdit'')',pageName));

% exception handler checkbox
Children.exceptionCheckbox = uicontrol( ...
    'Parent',             Children.addoptGroupbox, ...
    'Style',              'checkbox', ...
    'String',             'Protect against division by zero in production code', ...
    'Position',           ctrlPos.exceptionCheckbox, ...
    'Callback',           sprintf('tldlg(''%s'',gcbf,''exceptionCheckbox'')',pageName));

dlgdata.pageData{pageNum}.children = Children;


%-----------------------------------------------------------------------------------------
% FcnManageOutputControls manage control actions of output page
%
% INPUT ARGUMENTS
%   pageNum     number of current page
%   dlgfig      handle for dialog figure
%   dlgdata     dialog data
%   pageAction  action at one control of current page
%
% OUTPUT ARGUMENTS
%   dlgdata     modified dialog data
%   bModified   flag = 1, if dialog data are modified, =0 otherwise
%-----------------------------------------------------------------------------------------
function [dlgdata,bModified] = FcnManageOutputPage(pageNum,dlgfig,dlgdata,action)

Children = dlgdata.pageData{pageNum}.children;

% inputs edit field may be a number or a sequence of * and / signs
RexExpr = '([1-9]+[0-9]*)|([\*/]+)';
switch action
    % input signs were edited
    case 'inputsEdit'
        inputs = tl_deblank(get(Children.inputsEdit, 'String'), 2);
        bMatch = ds_regexp(RexExpr, inputs);
        if bMatch
            dlgdata.data.inputs = inputs;
        else
            beep;
        end
        bModified = 1;

    case 'exceptionCheckbox'
        dlgdata.data.exceptionhandling = get(Children.exceptionCheckbox,'Value');
        bModified = 1;

    otherwise
        [dlgdata, bModified1] = ...
            TLManageVariableCtrls('manage',pageNum,dlgfig,dlgdata,action,'output');
        [dlgdata, bModified2] = ...
            TLManageScalingCtrls('manage',pageNum,dlgfig,dlgdata,action,'output');
        bModified = bModified1 || bModified2;
end


%--------------------------------------------------------------------------
% FcnUpdateOutputPage updates the output controls
%
% INPUT ARGUMENTS
%   dlgdata     dialog data
%   dlgfig      figure handle of dialog
%   pageNum     page Number
%
% OUTPUT ARGUMENTS
%   dlgdata     modified dialog data
%--------------------------------------------------------------------------
function dlgdata = FcnUpdateOutputPage(dlgdata,dlgfig,pageNum)

Children = dlgdata.pageData{pageNum}.children;

% default control status for controls
if dlgdata.bIsFullVs
    defaultStatus = 'on';
else
    defaultStatus = 'inactive';
end
% number of inputs independend of blockset mode
inputsEditCtrlStatus        = struct('enable', 'on', 'string', '');
exceptionCheckboxCtrlStatus = struct('enable', defaultStatus, 'value', 0);

% if there is only one input, output is always scalar -> width and
% element controls are inactive
bSumOfInputVector = any(strcmp(dlgdata.data.inputs, {'1' '*' '/'}));
if bSumOfInputVector
    dlgdata.data.output.width = 1;
end

% update all variable controls
dlgdata = TLManageVariableCtrls('update', pageNum, dlgdata, 'output');
dlgdata = TLManageScalingCtrls('update', pageNum, dlgdata, 'output', []);

inputsEditCtrlStatus.string = dlgdata.data.inputs;
exceptionCheckboxCtrlStatus.value = dlgdata.data.exceptionhandling;

widthEditCtrlStatus = tl_get_control_userdata(Children.widthEdit);
widthDownButtonCtrlStatus = tl_get_control_userdata(Children.widthDownButton);
widthUpButtonCtrlStatus = tl_get_control_userdata(Children.widthUpButton);
elementEditCtrlStatus = tl_get_control_userdata(Children.elementEdit);
elementDownButtonCtrlStatus = tl_get_control_userdata(Children.elementDownButton);
elementUpButtonCtrlStatus = tl_get_control_userdata(Children.elementUpButton);
scalarExpCheckboxCtrlStatus = tl_get_control_userdata(Children.scalarExpCheckbox);
if bSumOfInputVector
    widthEditCtrlStatus.enable = 'inactive';
    widthDownButtonCtrlStatus.enable = 'off';
    widthUpButtonCtrlStatus.enable = 'off';
    elementEditCtrlStatus.enable = 'inactive';
    elementDownButtonCtrlStatus.enable = 'off';
    elementUpButtonCtrlStatus.enable = 'off';
    scalarExpCheckboxCtrlStatus.enable = 'off';
end

% write control status of extra controls to the control
extraCtrlsList = {'inputsEdit', 'exceptionCheckbox'};
standardCtrlsList = {
    'widthEdit', ...
    'widthDownButton', ...
    'widthUpButton', ...
    'elementEdit', ...
    'elementDownButton', ...
    'elementUpButton', ...
    'scalarExpCheckbox'};
ctrlsList = [extraCtrlsList standardCtrlsList];
for ctrlsNo = 1:length(ctrlsList)
    ctrl = Children.(ctrlsList{ctrlsNo});
    UserData = get(ctrl, 'UserData');
    UserData.ctrlStatus = eval([ctrlsList{ctrlsNo} 'CtrlStatus']);
    set(ctrl, 'UserData', UserData);
end

% set standard controls
TLManageVariableCtrls('setCtrls', pageNum, dlgfig, dlgdata);
TLManageScalingCtrls('setCtrls', pageNum, dlgfig, dlgdata);

% set non-standard controls
TLSetCtrlsStatus(dlgfig, Children, extraCtrlsList);
